//
//  AuthPlugin.swift
//  CooperSwift
//
//  Created by Mac on 2019/12/5.
//  Copyright © 2019 CooperSwift. All rights reserved.
//

import Foundation
import Moya

protocol AuthorizedTargetType: TargetType {
    // 返回是否需要授权
    var needsAuth: Bool { get }
}

struct AuthPlugin: PluginType {
    let token: String = ""
    // 获取令牌字符串方法
    let tokenClosure: () -> String?
    
    // 准备发起请求
    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        var request = request 
        guard let target = target as? AuthorizedTargetType, target.needsAuth else { /// 获取获取令牌字符串
            return request
        }
        if let token = tokenClosure() { /// 将token添加到请求头中
            request.addValue(token, forHTTPHeaderField: "Authorization")
        }
        return request
    }
}
